<?php
namespace App\Repositories\Summary;

use App\Models\Absence;
use App\Models\Attendance;
use App\Models\Egress;
use App\Models\Transportation;
use App\Models\User;
use App\Models\WorkTime;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;

class SummaryDBRepository implements SummaryRepository
{

    public function getPaginator(SummaryFilter $summaryFilter)
    {
        $summary = $this->getDBQuery($summaryFilter);
        $paginator = new LengthAwarePaginator($summary, $summary->count(), $summaryFilter->getPerPage());
        return $paginator;
    }

    protected function getDBQuery(SummaryFilter $summaryFilter)
    {

        $startTime = Carbon::parse(Carbon::parse('-30 days')->toDateString())->toDateTimeString();
        $endTime = Carbon::today()->toDateTimeString();
        $userQuery = User::query();


        if ($summaryFilter->getStartTime() && $summaryFilter->getEndTime()){
            $startTime = $summaryFilter->getStartTime();
            $endTime = $summaryFilter->getEndTime();
        }

        $workQuery = WorkTime::where('start_time', '>=', $startTime)
                ->where('start_time', '<=', $endTime);


        $work = $workQuery->get()->toArray();

        if ($name = $summaryFilter->getName()) {
            $userQuery->where('name', 'like', '%'.$name.'%');
        }

        if ($departmentName = $summaryFilter->getDepartmentName()) {
            $userQuery->whereHas('department' , function ($query) use($departmentName) {
                $query->where('name', 'like', '%'.$departmentName.'%');
            });
        }

        $users = $userQuery->get()->toArray();

        $summary = [];
        foreach ($users as $user){
            $summaryTemp = new User();
            $summaryTemp['user_id'] = $user['id'];
            $summaryTemp['name'] = $user['name'];
            //实际
            $summaryTemp['total_attendance'] = 0;
            //足额
            $summaryTemp['total_zue'] = 0;
            //应该
            $summaryTemp['total_yinggai'] = $workQuery->where('work_type', 1)->get()->count();
            //请假
            $summaryTemp['total_qingjia'] = 0;
            //外出
            $summaryTemp['total_waichu'] = 0;

            //非工作日加班
            //天数
            $summaryTemp['fgz_ts'] = 0;
            //足额
            $summaryTemp['fgz_zue'] = 0;
            //总加班时长
            $vertime = 0;
            //实际工作时长
            $summaryTemp['gzsc_sj'] = 0;
            //应该工作时长
            $summaryTemp['gzsc_yg'] = 0;
            //请假时长
            $summaryTemp['gzsc_qj'] = 0;
            //外出时长
            $summaryTemp['gzsc_wc'] = 0;
            //taxi
            $summaryTemp['taix'] = 0;

            //最早打卡时间数组
            $startTimes = [];
            //最晚打卡时间数组
            $endTimes = [];

            foreach ($work as $v) {
                $attendanceQuery = Attendance::query();
                $absence = Absence::query();
                $egress = Egress::query();

                $attendanceQuery->where('attendance_no', $user['attendance_no'])
                    ->where('name', $user['name']);
                $res = $attendanceQuery->where('register_time','like', '%'. substr($v['start_time'], 0, 10). '%')->get();

                if ($v['work_type'] == 1 && !$res->isEmpty()) {
                    $summaryTemp['total_attendance'] += 1;
                }

                if ($v['work_type'] == 2 && !$res->isEmpty()) {
                    $summaryTemp['fgz_ts'] += 1;
                }



                $defineAttendance = round((float)((strtotime($v['end_time'])-strtotime($v['start_time']))%86400/3600),1);
//                $res->map(function ($item) use ($defineAttendance, &$summaryTemp, $v, &$vertime,&$startTimes, &$endTimes ){
                 if (!$res->isEmpty()) {
                    $sortRes = $res->sortBy('register_time');
                    $startTime = $sortRes->first()->register_time;
                    $endTime = $sortRes->pop()->register_time;
                    $startTimes[] = Carbon::parse(substr($startTime,11))->timestamp;
                    $endTimes[] = Carbon::parse(substr($endTime,11))->timestamp;
                    $minute=round((float)((strtotime($endTime)-strtotime($startTime))%86400/3600),1);
                    if($v['work_type'] == 1 && $minute>$defineAttendance){
                        $summaryTemp['total_zue']+= 1;
                    }

                    if($v['work_type'] == 2 && $minute>$defineAttendance){
                        $vertime += $minute;
                        $summaryTemp['fgz_zue']+= 1;
                    }

                    if ($v['work_type'] == 1) {
                        $summaryTemp['gzsc_yg'] += $defineAttendance;
                    }

                    $summaryTemp['gzsc_sj'] += $minute;

                 }
//                });

                $absences = $absence->where('user_id', $user['id'])->where('absence_date', substr($v['start_time'], 0, 10))->get();
                if (!$absences->isEmpty()){
                    $summaryTemp['total_qingjia'] += 1;
                    $ab = $absences->first();
                    $summaryTemp['gzsc_qj']+= round($ab->end_time - $ab->start_time, 1);
                }


                $egreses = $egress->where('user_id', $user['id'])->where('dates', substr($v['start_time'], 0, 10))->get();
                if (!$egreses->isEmpty()){
                    $summaryTemp['total_waichu'] += 1;
                    $eg = $egreses->first();
                    $summaryTemp['gzsc_wc'] += round($eg->end_time - $eg->start_time, 1);
                }


                $summaryTemp['taix'] += Transportation::where('riding_time','like', '%'. substr($v['start_time'], 0, 10). '%')
                    ->where('user_id', $user['id'])
                    ->get()
                    ->count();


            }

            //实际
            $summaryTemp['total_attendance'] +=  $summaryTemp['total_waichu'];
            //实/应该
            if ($summaryTemp['total_yinggai'] == 0) {
                $summaryTemp['shiyingbi'] = '0%';
            }else{
                $summaryTemp['shiyingbi'] = round($summaryTemp['total_attendance']/$summaryTemp['total_yinggai']*100,1) . '%';
            }
            //不足
            $summaryTemp['total_buzu'] = $summaryTemp['total_attendance'] - $summaryTemp['total_zue'];
            //个应
            $summaryTemp['total_geying'] = $summaryTemp['total_yinggai'] - $summaryTemp['total_qingjia'];
            //实际/个应
            if ($summaryTemp['total_geying'] == 0){
                $summaryTemp['shigeyingbi'] = '0%';
            }else{
                $summaryTemp['shigeyingbi'] = round($summaryTemp['total_attendance']/$summaryTemp['total_geying']*100,1) . '%';
            }

            //非工作日加班
            //日均
            if ($summaryTemp['fgz_ts'] == 0){
                $summaryTemp['fgz_rj'] =0;
            }else{
                $summaryTemp['fgz_rj'] = round($vertime/$summaryTemp['fgz_ts'],1);
            }

            //工作时长
            //实际
            $summaryTemp['gzsc_sj'] += $summaryTemp['gzsc_wc'];
            //实际工作时长/应该工作时长
            if ($summaryTemp['gzsc_yg'] == 0){
                $summaryTemp['gzsc_sjb'] = '0%';
            }else{
                $summaryTemp['gzsc_sjb'] = round($summaryTemp['gzsc_sj']/$summaryTemp['gzsc_yg']*100,1) . '%';

            }
            //个应
            $summaryTemp['gzsc_gy'] = $summaryTemp['gzsc_yg'] - $summaryTemp['gzsc_qj'];
            //实际/个应
            if ($summaryTemp['gzsc_gy'] == 0){
                $summaryTemp['gzsc_sjgyb'] = '0%';
            }else{
                $summaryTemp['gzsc_sjgyb'] = round($summaryTemp['gzsc_sj']/$summaryTemp['gzsc_gy']*100,1) . '%';

            }
            //日均
            if ($summaryTemp['total_zue'] == 0){
                $summaryTemp['gzsc_rj'] = 0;
            }else{
                $summaryTemp['gzsc_rj'] = round($summaryTemp['gzsc_gy']/$summaryTemp['total_zue'],1);

            }

            //上下班时间
            //均到
            $startTotaltimes = 0;
            foreach ($startTimes as $start){
                $startTotaltimes += $start;
            }
            if (count($startTimes) == 0) {
                $summaryTemp['sxbsj_jd'] = '--:--';
            }else{
                $summaryTemp['sxbsj_jd'] = date('H:i' ,$startTotaltimes/count($startTimes));
            }

            //均离
            $endTotaltimes = 0;
            foreach ($endTimes as $end){
                $endTotaltimes += $end;
            }
            if (count($startTimes) == 0) {
                $summaryTemp['sxbsj_jl'] = '--:--';
            }else{
                $summaryTemp['sxbsj_jl'] = date('H:i' ,$endTotaltimes/count($endTimes));
            }

            //最早
            $startTotaltimes = array_sort($startTotaltimes);
            $summaryTemp['sxbsj_zz'] = date('H:i' ,$startTotaltimes[0]);
            //最晚
            $endTotaltimes = array_sort($endTotaltimes);
            $summaryTemp['sxbsj_zw'] = date('H:i' ,array_pop($endTotaltimes));


           $summary[] = $summaryTemp;

        }
        return collect($summary);
    }

}
